﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Transport.Channels;

namespace YanShu.Utils
{
    //代理数据解码
    public class ProxyMessageDecoder : LengthFieldBasedFrameDecoder
    {
        public static byte HEADER_SIZE = 4;

        public static int TYPE_SIZE = 1;

        public static int SERIAL_NUMBER_SIZE = 8;

        public static int URI_LENGTH_SIZE = 1;


        public ProxyMessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip)
            : base(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip)
        {

        }


        public ProxyMessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, bool failFast)
            : base(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, failFast)
        {

        }
        //按编码规则进行解码操作
        protected override object Decode(IChannelHandlerContext context, IByteBuffer input2)
        {
            try
            {
                IByteBuffer input = (IByteBuffer)base.Decode(context, input2);
                if (input == null) {
                    return null;
                }


                if (input.ReadableBytes < HEADER_SIZE)
                {
                    return null;
                }
                int frameLength = input.ReadInt();
                if (input.ReadableBytes < frameLength )
                {
                    return null;
                }

                ProxyMessage proxyMessage = new ProxyMessage();

                byte type = input.ReadByte();

                long sn = input.ReadLong();

                proxyMessage.SetSerialNumber(sn);

                proxyMessage.SetType(type);

                
                byte uriLength = input.ReadByte();
                byte[] uriBytes = new byte[uriLength];
                input.ReadBytes(uriBytes);
                proxyMessage.SetUri(Encoding.UTF8.GetString(uriBytes));

                //存放代理数据
                byte[] data = new byte[frameLength - TYPE_SIZE - SERIAL_NUMBER_SIZE - URI_LENGTH_SIZE - uriLength];
                input.ReadBytes(data);
                proxyMessage.SetData(data);

                input2.Release();
                return proxyMessage;

            }
            catch (Exception e)
            {
                MainWindow.SetText(e.ToString());
            }
            return null;

        }

    }
}
